﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ACEPAPI.EPAPI
{
    /// <summary>
    /// ESC/POS命令简化与重命名
    /// </summary>
    public static class CommandsA
    {
        /// <summary>
        /// 打印数据
        /// </summary>
        /// <param name="data">要打印的数据</param>
        /// <param name="printerAddress">打印机IP地址</param>
        /// <param name="printerPort">打印机IP端口</param>
        /// <param name="info">返回信息</param>
        public static bool SendData(this byte[] data, string printerAddress, int printerPort, out string info, bool saveToLocal = false)
        {
            //检测
            System.Net.IPAddress ipAdd;
            if (!System.Net.IPAddress.TryParse(printerAddress, out ipAdd))
            {
                info = "IP地址错误";
                return false;
            }

            if (printerPort <= 0 || printerPort > 65535)
            {
                info = $"IP地址端口：{printerPort}无效";
                return false;
            }

            //发送数据
            using (Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                soc.NoDelay = true;
                soc.Connect(ipAdd, printerPort);
                soc.Send(data);
            }

            //保存数据到本地
            if (saveToLocal)
            {
                string tempFile = "esc_pos.temp";
                if (File.Exists(tempFile))
                {
                    try
                    {
                        File.Delete(tempFile);
                    }
                    catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
                    {
                        tempFile = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{tempFile}";
                    }
                }
                File.WriteAllBytes(tempFile, data);
                File.Copy(tempFile, printerAddress, true);
            }
            info = "true";
            return true;
        }
        
        /// <summary>
        /// 字符串转换成要发送的byte[]
        /// </summary>
        /// <param name="data">字符串</param>
        /// <returns></returns>
        public static byte[] Print(string data)
        {
            data = data.Replace("\r\n", "\n");
            data = data.Replace("\r", "\n");
            return data.ToCharArray().Select(t => (byte)t).ToArray();
        }

        /// <summary>
        /// 字符串转换成要发送的数据行byte[]
        /// </summary>
        /// <param name="printLine">字符串</param>
        /// <returns></returns>
        public static byte[] PrintLine(string printLine)
        {
            if(printLine=="" || printLine == null)
            {
                return Print("\n");
            }
            else
            {
                return Print($"printLine{"\n"}");
            }
        }
    }
}
